<template>
	<view class="page-content">
		<view class="form">
			<view class="form-content">
				<canvas class="form-content__canvas" canvas-id="mycanvas" @touchstart="touchstart" 
					:style="{width:width +'px',height:height +'px'}" @touchmove="touchmove" @touchend="touchend" disable-scroll="true"></canvas>
			</view>
			<view class="form-footer">
				<button class="form-footer__reset" @click="handleCancel">返回</button>
				<button class="form-footer__save"  @click="handleReset">重置</button>
				<button class="form-footer__preview" @click="handleConfirm">保存</button>
			</view>
		</view>
	</view>
</template>
<script>
var x = 20;
var y = 20;
var tempPoint = []; //用来存放当前画纸上的轨迹点
var type = '';
let that;
let canvasw;
let canvash;
export default {
  data() {
    return {
      ctx: '', //绘图图像
      points: [], //路径点集合,
	  cachePic:{},
	  headers: {"content-type":"application/x-www-form-urlencoded"},
	  action:'/api/manage/common/onlyUploadImage',
	  model:{},
      width: 0,
      height: 0
    };
  },
  mounted() {},
 
  onLoad(option) {
    that = this;
	let token = this.$storage.getData("token");
	if (token) {
		this.headers.Authorization = token
	}
    console.log(option);
    this.model.id = option.hid;
    // type = option.type;
	
    this.ctx = uni.createCanvasContext('mycanvas', this); //创建绘图对象
    //设置画笔样式
    this.ctx.lineWidth = 4;
    this.ctx.lineCap = 'round';
    this.ctx.lineJoin = 'round';
 
    uni.getSystemInfo({
      success: function (res) {
        that.width = res.windowWidth * 0.8;
        that.height = res.windowHeight * 0.85;
      }
    });
  },
 
  methods: {
    //触摸开始，获取到起点
    touchstart: function (e) {
      let startX = e.changedTouches[0].x;
      let startY = e.changedTouches[0].y;
      let startPoint = {
        X: startX,
        Y: startY
      };
 
      /* **************************************************
				    #由于uni对canvas的实现有所不同，这里需要把起点存起来
				 * **************************************************/
      this.points.push(startPoint);
 
      //每次触摸开始，开启新的路径
      this.ctx.beginPath();
    },
 
    //触摸移动，获取到路径点
    touchmove: function (e) {
      let moveX = e.changedTouches[0].x;
      let moveY = e.changedTouches[0].y;
      let movePoint = {
        X: moveX,
        Y: moveY
      };
      this.points.push(movePoint); //存点
      let len = this.points.length;
      if (len >= 2) {
        this.draw(); //绘制路径
      }
      tempPoint.push(movePoint);
    },
 
    // 触摸结束，将未绘制的点清空防止对后续路径产生干扰
    touchend: function () {
      this.points = [];
    },
 
    /* ***********************************************	
			#   绘制笔迹
			#   1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
			#   2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
			#   3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
			************************************************ */
    draw: function () {
      let point1 = this.points[0];
      let point2 = this.points[1];
      this.points.shift();
      this.ctx.moveTo(point1.X, point1.Y);
      this.ctx.lineTo(point2.X, point2.Y);
      this.ctx.stroke();
      this.ctx.draw(true);
    },
 
    handleCancel() {
      uni.navigateBack({
        delta: 1
      });
    },
 
    //清空画布
    handleReset: function () {
      console.log('handleReset');
      that.ctx.clearRect(0, 0, that.width, that.height);
      that.ctx.draw(true);
      tempPoint = [];
    },
	async uploadFiles(path){
	   let that =this
	   console.log('uploadFile',path,that.$api.getUrl(that.action),that.headers)
	    await uni.uploadFile({
	      url: this.$api.getUrl(that.action)+"?type=0",    
	      filePath:path, 
	      name: 'file', 
					// application/x-www-form-urlencoded
	      header:that.headers,
	      success: res => {    
	      let data=JSON.parse(res.data) //返回的是字符串，需要转成对象格式   
	      if(data.code==0){ 
	     var str = data.data.split("/")
	     var fileName = str[str.length-1]
		 that.cachePic={name:fileName,url:data.data}
		 this.UpdateData()
		 return data
						
	       }
	      },   
	     fail: () => {
	      console.log("err");
	     }   
	    })   
	    
	},
    //将签名笔迹上传到服务器，并将返回来的地址存到本地
    handleConfirm: function () {
		var that = this
		console.log(that.$api.getUrl(that.action))
      if (tempPoint.length == 0) {
        uni.showToast({
          title: '请先签名',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      uni.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function (res){
          let tempPath = res.tempFilePath;
		  that.uploadFiles(tempPath)
     //      const ctx = uni.createCanvasContext('camCacnvs', that);
     //      ctx.translate(0, that.width);
     //      ctx.rotate((-90 * Math.PI) / 180);
     //      ctx.drawImage(tempPath, 0, 0, that.width, that.height);
     //      ctx.draw();
     //      setTimeout(() => {
			  
			  // //保存签名图片到本地
     //        uni.canvasToTempFilePath(
     //          {
     //            canvasId: 'camCacnvs',
     //            success: function (res) {
					// //这是签名图片文件的本地临时地址
					//  console.log('tempFilePath',res.tempFilePath)
     //              let path = res.tempFilePath;
                 
     //            },
     //            fail: err => {
     //              console.log('fail', err);
     //            }
     //          },
     //          this
     //        );
     //      }, 200);
        }
      });
    },
	UpdateData(){
		this.model.signaturePath = JSON.stringify(this.cachePic)
		this.$request.postU(this.$api.owner.updateOnlyOwner,this.model).then(res=>{
			if(res.code==0) {
				uni.showToast({
				title: '签名保存成功'
				})
				this.$storage.setData('refresh','1')
				setTimeout(() =>{
								uni.navigateBack({delta: 1  //返回两层页面
								});		
							}, 1000);
				
			}
		});
	}
  }
};
</script>
 
<style lang="scss" scoped>
	/*
	* 横屏后的适配方案
	* @param $rpx为需要转换的字号
	* @参考 https://blog.csdn.net/sdfsfsdscd/article/details/91375066
	**/
	@function tovmin($rpx) {
		@return #{$rpx * 100 / 750}vmin;
	}
	.page-content {
		width: 100vw;
		height: 100vh;
		.form {
			display: flex;
			flex-direction: column;
			width: 100%;
			height: 100%;
			.form-content {
				width: 100%;
				height: 100%;
				&__canvas {
					height: calc(100vh - tovmin(20) - tovmin(120) - constant(safe-area-inset-bottom));
					height: calc(100vh - tovmin(20) - tovmin(120) - env(safe-area-inset-bottom));
					width: 100vw;
				}
			}
			.form-footer {
				padding-top: tovmin(20);
				height: calc(tovmin(120) + constant(safe-area-inset-bottom));
				height: calc(tovmin(120) + env(safe-area-inset-bottom));
				width: 100%;
				display: flex;
				flex-direction: row;
				BACkground: #FFFFFF;
				box-shadow: 0 tovmin(4) tovmin(20) tovmin(2) rgba(183, 183, 183, 0.20);
				button {
					width: 20vw;
					height: tovmin(88);
					line-height: tovmin(88);
					border-radius: tovmin(48);
					text-align: center;
					font-size: tovmin(36);
					font-weight: bold;
				}
				button::after {
					border: none;
				}
				&__reset {
					color: #008AFE;
					border: tovmin(1) solid #008AFE;
				}
				&__save {
					BACkground-image: linear-gradient(135deg, #1BC5FF 0%, #008AFE 100%);
				}
				&__preview {
					color: #008AFE;
					border: tovmin(1) solid #008AFE;
				}
			}
		}
	}
</style>